package sde.actor.railway;
import sde.actor.*;

public class Sbarra extends Actor implements SbarraIF{
	public static final byte CREATED=0, OPENED=1, OPENING=2, 
		                             CLOSED=3, CLOSING=4;
	private static class OperationComplete extends Message{}
	private OperationComplete done=new OperationComplete();
	private Timer timer=new Timer();
	private double delay;
	private ControlloreIF controller; //porta di uscita - acquaintance
	public Sbarra(){ become( CREATED ); }
	public void handler( Message m ){
		switch( currentStatus() ){
			case CREATED:
				if( m instanceof Init ){
				        controller=((Init)m).controller;
				        delay=((Init)m).delay;
				        System.out.println("Sbarra aperta @"+now());
				        become( OPENED );
				} break;
			case OPENED:
				if( m instanceof ToClose ){
				     timer.set( done, this, delay );
				     System.out.println("Sbarra in chiusura @"+now());
				     become( CLOSING );
				} break;
			case CLOSING:
				if( m==done ){
				     controller.send( new ControlloreIF.Closed() );
				     System.out.println("Sbarra chiusa @"+now());
				     become( CLOSED );
				} break;
			case CLOSED:
				if( m instanceof ToOpen ){
				     timer.set( done, this, delay );
				     System.out.println("Sbarra in apertura @"+now());
				     become( OPENING );
				} break;
			case OPENING:
				if( m instanceof ToClose ){
				     double timeRemaining=timer.timeRemaining();
				     timer.reset();
				     timer.set( done, this, delay-timeRemaining );
				     System.out.println("Sbarra in chiusura @"+now());
				     become( CLOSING );
				}
				else if( m==done ){
				     controller.send( new ControlloreIF.Opened() );
				     System.out.println("Sbarra aperta @"+now());
				     become( OPENED );
				}
	   }//switch
   }//handler
}//Sbarra

